﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Dynamic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using cs3750.Models;

namespace cs3750.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(Member member)
        {
        
            if (ModelState.IsValid)
            {
                try
                {
                    var connection = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["databaseConnection"].ConnectionString);
                    var cmd = connection.CreateCommand();
                    cmd.Parameters.Add("@Name", member.Name);
                    cmd.CommandText = "INSERT into Member(Names) values(@Name)";
                    connection.Open();
                    cmd.ExecuteNonQuery();
                }
                catch (Exception ex)
                {
                    var e = ex.Message;
                }
                return RedirectToAction("Names");
            }
            return View();
        }

        public ActionResult Names()
        {
            var connection = new SqlConnection(System.Configuration.ConfigurationManager.
                ConnectionStrings["databaseConnection"].ConnectionString);

            connection.Open();
            var cmd = connection.CreateCommand();
            cmd.CommandText = "SELECT Names FROM Member";

            var members = new List<Member>();

            using (var rdr = cmd.ExecuteReader())
            {
                while (rdr.Read())
                {
                    var member = new Member();
                    member.Name = rdr.GetValue(0) == null ? string.Empty : rdr.GetString(0);
                    members.Add(member);
                }
            }

            return View(members);
        }

    }
}
